package com.shengwei.truck.driver.view.ui.task.pounds;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Toast;

import androidx.core.content.FileProvider;
import androidx.lifecycle.Observer;

import com.baidu.location.BDLocation;
import com.google.gson.Gson;
import com.lzy.okhttpserver.listener.UploadListener;
import com.lzy.okhttpserver.task.ExecutorWithListener;
import com.lzy.okhttpserver.upload.UploadInfo;
import com.lzy.okhttpserver.upload.UploadManager;
import com.shengwei.truck.driver.utils.MyToast;
import com.shengwei.truck.driver.view.ui.app.MyApplication;
import com.shengwei.truck.driver.R;
import com.shengwei.truck.driver.bean.DeleteInfo;
import com.shengwei.truck.driver.bean.FileUrlBean;
import com.shengwei.truck.driver.bean.ImageItem;
import com.shengwei.truck.driver.bean.JsonPoundsState;
import com.shengwei.truck.driver.bean.MyConstant;
import com.shengwei.truck.driver.bean.PoundsListBean;
import com.shengwei.truck.driver.bean.Result;
import com.shengwei.truck.driver.bean.User;
import com.shengwei.truck.driver.databinding.ActivityPostPoundsListBinding;
import com.shengwei.truck.driver.permission.RxjavaPermissionUtil;
import com.shengwei.truck.driver.utils.DateTimeUtils;
import com.shengwei.truck.driver.utils.IntentConstants;
import com.shengwei.truck.driver.utils.MyLogCat;
import com.shengwei.truck.driver.view.adapter.task.ImagePublishAdapter;
import com.shengwei.truck.driver.view.adapter.task.TaskGridAdapter;
import com.shengwei.truck.driver.view.selfview.SelectPicPopupWindow;
import com.shengwei.truck.driver.view.ui.BaseActivity;
import com.shengwei.truck.driver.view.ui.mine.userinfo.LoginActivity;
import com.shengwei.truck.driver.view.ui.task.PhotoGallyActivity;
import com.shengwei.truck.driver.view.ui.task.TaskDetailActivity;
import com.shengwei.truck.driver.vm.PostPoundsViewModel;
import com.tbruyelle.rxpermissions2.Permission;
import com.tbruyelle.rxpermissions2.RxPermissions;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONObject;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.Serializable;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import io.reactivex.functions.Consumer;
import okhttp3.Response;
import okhttp3.ResponseBody;
/**
 * 上传榜单页面
 */
public class PostPoundsListActivity extends BaseActivity<PostPoundsViewModel, ActivityPostPoundsListBinding> implements View.OnClickListener,
        ExecutorWithListener.OnAllTaskEndListener{
    public  List<ImageItem> mDataList;
    private String TAG = "PostPoundsListActivity";
    private String mCurTaskId;
    private String mCurTaskNo;
    private String mUnit;
    private SelectPicPopupWindow mSelectPicPopupWindow;
    private File picSaveDirectory; //图片存放的目录
    private File takePhotoFile;   //拍照得到的图片文件
    private File cropSmallFile;   //裁剪得到的图片文件
    private int mFromPage = 0;  //1当前任务提交榜单； 2异常任务
    private String mPoundState = ""; //榜单目前状态，3出厂磅单已上传，0已上传收货磅单，-1还未上传任何磅单
    private ProgressDialog mLocProgressDialog;
    private PoundsListBean mPoundsListInfo;

    //出厂磅单图片列表数据
    public List<ImageItem> mDataListOut = new ArrayList<ImageItem>(); //出厂磅单图片列表
    public List<ImageItem> mDataListOutShow = new ArrayList<ImageItem>();//回显 出厂磅单图片列表
    public List<ImageItem> mDataListRecv = new ArrayList<ImageItem>(); //收货磅单图片列表
    //提交磅单时，要上传的多张图片URL数组
    ArrayList<FileUrlBean> mOutWeighingListUrls = new ArrayList<>();     //出厂磅单多张图片URL
    ArrayList<FileUrlBean> mReceiveWeighingListUrls = new ArrayList<>(); //收货磅单多张图片URL
    ArrayList<FileUrlBean> mListUrls = new ArrayList<>(); //异常磅单
    //GRID网格要回显的已上传的出厂磅单多张图片
    ArrayList<FileUrlBean> mOutPoundsShowImgs; //回显多张图片URL
    //收货磅单图片列表适配器
    private ImagePublishAdapter mAdapterOut;
    private TaskGridAdapter mAdapterOutShow;
    private ImagePublishAdapter mAdapterRecv;
    private int mCurClickGridType;
    private int mMaxImgSize = 5;
    private String mCarNum; //车牌号

    @Override
    public void onCreate(Bundle savedInstanceState) {
        MyLogCat.i(TAG, "onCreate postFile mPoundState="+mPoundState);
        super.onCreate(savedInstanceState);
        mkDirForPic();
        getLastIntent();
        initView();
        initLiveDataObersve();
        checkPoundsState();
        //多线程上传文件
        initThreadPool();
        registEvent();
    }
    public void registEvent(){
        if(!EventBus.getDefault().isRegistered(PostPoundsListActivity.this)){
            EventBus.getDefault().register(PostPoundsListActivity.this);
        }
    }
    public void unRegistEvent(){
        if (EventBus.getDefault().isRegistered(this)){
            EventBus.getDefault().unregister(this);
        }
    }
    /**
     * 初始化线程池
     */
    private void initThreadPool() {
        UploadManager.getInstance(this).getThreadPool().setCorePoolSize(1);
        UploadManager.getInstance(this).getThreadPool().getExecutor().addOnAllTaskEndListener(this);
    }

    /**
     * 停止所有上传文件的任务
     */
    public void stopAllPostFileTask() {
        try {
            //清除所有任务对象
            List<UploadInfo> allTask = UploadManager.getInstance(PostPoundsListActivity.this).getAllTask();
            for(UploadInfo uploadInfo: allTask) {
                uploadInfo.getTask().cancel(true);
            }
            allTask.clear();  //清除所有任务对象
            /*gxw+e*/
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        return;
    }

    @Override
    protected void onResume() {
        MyLogCat.i(TAG,"onResume");
        notifyDataChanged(mCurClickGridType);
        super.onResume();
    }

    /**
     * 刷新 出厂磅单图片GRID列表 或者 收货磅单GRID
     * @param poundsType：要刷新的磅单GRID列表类型：出厂，收货，出厂回显grid
     */
    private void notifyDataChanged(int poundsType) {
        if(poundsType == IntentConstants.GRID_OUT_TYPE){  //出厂磅单图片列表刷新
            mAdapterOut.notifyDataSetChanged();
        }
        else if(poundsType == IntentConstants.GRID_RECV_TYPE){        //收货磅单图片列表刷新
            mAdapterRecv.notifyDataSetChanged();
        }
        else if(poundsType == IntentConstants.GRID_OUT_SHOW_TYPE){   //刷新回显的图片列表数据
            mAdapterOutShow.notifyDataSetChanged();
        }
    }
    @Override
    protected void onStop() {
        MyLogCat.i(TAG," postFile onStop");
        if(mLocProgressDialog != null && mLocProgressDialog.isShowing()){
            mLocProgressDialog.dismiss();
        }
        stopAllPostFileTask();
        super.onStop();
    }

    @Override
    protected void onPause() {
        MyLogCat.i(TAG,"onPause");
        super.onPause();
    }
    @Override
    protected void onDestroy() {
        MyLogCat.i(TAG,"postFile onDestroy");
        unRegistEvent();
        UploadManager.getInstance(PostPoundsListActivity.this).getThreadPool().getExecutor().removeOnAllTaskEndListener(this);
        super.onDestroy();
    }

    private void initView() {
        mDataBinding.btPostPoundsList.setOnClickListener(this);
        mDataBinding.btTaskDetail.setOnClickListener(this);
        //默认传递车牌号
        if(!TextUtils.isEmpty(mCarNum)){
            mDataBinding.edtCarNum.setText(mCarNum);
            mDataBinding.edtCarNum2.setText(mCarNum);
        }
        //异常磅单重新提交
        if(mFromPage == 2){
            mDataBinding.outPoundsLayout.setVisibility(View.VISIBLE);
            mDataBinding.recvPoundsLayout.setVisibility(View.VISIBLE);
            mMaxImgSize = 1;
        }
        //初始化出厂，收货
        initImgGrid();
    }

    /**
     * 初始化出厂图片选择列表
     */
    public void initOutImgGrid(){
        mDataBinding.gridOutPoundsList.setSelector(new ColorDrawable(Color.TRANSPARENT));
        mAdapterOut = new ImagePublishAdapter(this, mDataListOut,mMaxImgSize);
        mDataBinding.gridOutPoundsList.setAdapter(mAdapterOut);
        mDataBinding.gridOutPoundsList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                mCurClickGridType = IntentConstants.GRID_OUT_TYPE;
                if (position == getOutFactoryImgSize()) {
                    showSelPicWindow(IntentConstants.GRID_OUT_TYPE);
                }
                else {
                    goImageZoomActivity(position,mDataListOut,IntentConstants.GRID_OUT_TYPE);
                }
            }
        });
    }

    /**
     * 初始化卸货磅单图片选择列表
     */
    public void initRecvImgGrid(){
        mDataBinding.gridRecvPoundsList.setSelector(new ColorDrawable(Color.TRANSPARENT));
        mAdapterRecv = new ImagePublishAdapter(this, mDataListRecv,mMaxImgSize);
        mDataBinding.gridRecvPoundsList.setAdapter(mAdapterRecv);
        mDataBinding.gridRecvPoundsList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                mCurClickGridType = IntentConstants.GRID_RECV_TYPE;
                if (position == getRecvFactoryImgSize()) {
                    showSelPicWindow(IntentConstants.GRID_RECV_TYPE);
                }
                else {
                    mCurClickGridType = IntentConstants.GRID_RECV_TYPE;
                    goImageZoomActivity(position,mDataListRecv,IntentConstants.GRID_RECV_TYPE);
                }
            }
        });
    }

    /**
     * 回显出厂磅单图片列表
     */
      public void showOutImgGrid(ArrayList<FileUrlBean> fileUrls){
        mDataBinding.gridOutPoundsShowList.setSelector(new ColorDrawable(Color.TRANSPARENT));
        mAdapterOutShow = new TaskGridAdapter(PostPoundsListActivity.this, fileUrls);
        mDataBinding.gridOutPoundsShowList.setAdapter(mAdapterOutShow);
        mDataBinding.gridOutPoundsShowList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                goPhotoGallyActivity(position,mOutPoundsShowImgs);
            }
        });
    }

    /**
     * 去显示原图 页面
     * @param position
     * @param imgList
     * @param gridType
     */
    public void goImageZoomActivity(int position,List<ImageItem> imgList,int gridType){
        Intent intent = new Intent(PostPoundsListActivity.this, ImageZoomActivity.class);
        intent.putExtra(IntentConstants.EXTRA_IMAGE_LIST, (Serializable) imgList);
        intent.putExtra(IntentConstants.EXTRA_CURRENT_IMG_POSITION, position);
        intent.putExtra(IntentConstants.EXTRA_GRID_TYPE, gridType);
        startActivity(intent);
    }


    public void goPhotoGallyActivity(int curPosition,ArrayList<FileUrlBean> imgUrls){
        Intent intent = new Intent(PostPoundsListActivity.this, PhotoGallyActivity.class);
        intent.putExtra(IntentConstants.EXTRA_IMAGE_LIST, (Serializable) imgUrls);
        intent.putExtra(IntentConstants.EXTRA_CURRENT_IMG_POSITION, curPosition);
        startActivity(intent);
    }



    /**
     * 初始化 出厂 与 收货 图片,回显示出厂图片3个grid列表
     */
    public void initImgGrid() {
        initOutImgGrid();
        initRecvImgGrid();
    }

    /**
     * 获取到 “出厂磅单图片” 照片数量
     * @return
     */
    private int getOutFactoryImgSize() {
        return mDataListOut == null ? 0 : mDataListOut.size();
    }

    /**
     * 获取到 “收货磅单图片” 照片数量
     * @return
     */
    private int getRecvFactoryImgSize() {
        return mDataListRecv == null ? 0 : mDataListRecv.size();
    }

    /**
     * 获取 “回显出厂磅单图片”的 照片数量
     * @return
     */
    private int getOutFactoryShowImgSize() {
        return mDataListOutShow == null ? 0 : mDataListOutShow.size();
    }
    /**
     * 请求我的位置
     *
     * @param isShowProgressBar 是否显示进度框
     */
    public void requestMyLocation(boolean isShowProgressBar) {
        if (isShowProgressBar) {
            if (mLocProgressDialog == null) {
                mLocProgressDialog = new ProgressDialog(this);
            }
            //gxw-locProgressDialog.setCancelable(false);
            if(!PostPoundsListActivity.this.isFinishing()){
                mLocProgressDialog.setMessage("正在确定你的位置,若时间过长请重新尝试……");
                mLocProgressDialog.show();
            }
        }
        MyApplication.startLocService(); //必须加这一句，因为有时候定位服务关闭了，底下的代码就失效了
        MyApplication.mLocationService.requestLocation();
    }


    /**
     * 获取到了位置后，再上传磅单（包括出厂磅单与收货磅单）
     * @param bdLocation
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onGetMessage(BDLocation bdLocation) {
        if(mLocProgressDialog != null && mLocProgressDialog.isShowing() ){
            mLocProgressDialog.dismiss();
        }
        MyLogCat.i(TAG,"postFile onGetMessage lat="+bdLocation.getLatitude());
        double lat = bdLocation.getLatitude();  //纬度
        double lng = bdLocation.getLongitude(); //经度
        unRegistEvent();
        if(mPoundsListInfo != null){

            if(mFromPage != 2){  //正常磅单上传
                if(mPoundState.equals("-1")){   //未上传任何磅单，这次将上传出厂磅单经纬度
                    mPoundsListInfo.laLat = String.valueOf(lat);
                    mPoundsListInfo.laLng = String.valueOf(lng);
                }
                else if(mPoundState.equals("3")){  //出货磅单已上传，这次将上传收货磅单
                    mPoundsListInfo.uaLat = String.valueOf(lat);
                    mPoundsListInfo.uaLng = String.valueOf(lng);
                }

            }else{  //异常磅单重新上传,不上传经纬度
               ;
            }

            String jsonPoundsInfo= new Gson().toJson(mPoundsListInfo, PoundsListBean.class);
            MyLogCat.i(TAG,"postFile json of the poundsListBean="+jsonPoundsInfo);
            mViewModel.postPoundsListInfo(mPoundsListInfo);
        }else{
            MyLogCat.i(TAG,"postFile in onGetMessage 要上传的磅单数据位空" );
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onDeleteGridItem(DeleteInfo deleteInfo) {
        int gridType = deleteInfo.getGridType();
        int removePosition = deleteInfo.getPosition();
        switch (gridType){
            case IntentConstants.GRID_OUT_TYPE:
                mDataListOut.remove(removePosition);
                break;
            case IntentConstants.GRID_OUT_SHOW_TYPE:
                mDataListOutShow.remove(removePosition);
                break;
            case IntentConstants.GRID_RECV_TYPE:
                mDataListRecv.remove(removePosition);
                break;
        }
    }

    /**
     * 检查磅单状态
     */
    public void checkPoundsState() {
        if(!TextUtils.isEmpty(mCurTaskId))
            mViewModel.checkPoundsState(mCurTaskId);
        else{
            String tip = this.getResources().getString(R.string.task_id_not_empty);
            MyToast.showToastCenter(new WeakReference<>(PostPoundsListActivity.this),tip,Toast.LENGTH_SHORT,true);
        }
        return;
    }
    /**
     * 获取上页传递过来的数据
     */
    public void getLastIntent() {
        Intent i = this.getIntent();
        Bundle bundle = i.getExtras();
        if(bundle != null) {
            mCurTaskId = bundle.getString("taskId");
            mCurTaskNo = bundle.getString("taskNo");
            mUnit = bundle.getString("unit");
            mFromPage = bundle.getInt("fromPage");
            mCarNum = bundle.getString("carNum");
            if(!TextUtils.isEmpty(mCurTaskNo)) {
                mDataBinding.tvTaskNum.setText(mCurTaskNo);
            }
            if(!TextUtils.isEmpty(mUnit)) {
                mDataBinding.setUnit(mUnit);
            }
        }
    }

    /**
     * 创建liveData观察者，用于监听数据变化，从而更新UI
     */
    private void initLiveDataObersve() {
        //监听 检查磅单状态借口返回的数据
        mViewModel.getCheckPoundsStateLiveData().observe(this, new Observer<Result<JsonPoundsState>>() {
            @Override
            public void onChanged(Result<JsonPoundsState> postFileDataResult) {
                postFileDataResult.handler(new OnCallback<JsonPoundsState>() {
                    @Override
                    public void onSuccess(JsonPoundsState data) {
                        updatePoundsUI(data);
                    }

                    @Override
                    public void onFailure(String msg) {
                        dismissDlg();
                        if(msg != null){
                            MyLogCat.i(TAG,msg);
                            String[] errMsg = msg.split(";");
                            int code = Integer.parseInt(errMsg[0]);
                            String tip = errMsg[1];
                            WeakReference<Context> contextWeakReference =  new WeakReference<>(getApplicationContext());
                            //401,token过时; 403没有权限
                            if(code == 401 || code == 403) {
                                User user = User.getInstance(getApplicationContext());
                                user.setToken("");
                                Intent i = new Intent(PostPoundsListActivity.this, LoginActivity.class);
                                startActivity(i);
                            }
                        }
                        mDataBinding.mainLayout.setVisibility(View.VISIBLE);
                        mDataBinding.outPoundsLayout.setVisibility(View.VISIBLE);
                        mDataBinding.recvPoundsLayout.setVisibility(View.VISIBLE);
                    }
                });


            }
        });

        //监听上传榜单信息接口的结果
        mViewModel.getPoundsLiveData().observe(this, new Observer<Result<String>>() {
            @Override
            public void onChanged(Result<String> result) {
                result.handler(new OnCallback<String>() {
                    @Override
                    public void onSuccess(String data) {
                        String tip = PostPoundsListActivity.this.getResources().getString(R.string.post_pounds_list_ok);
                        MyToast.showToastCenter(new WeakReference<>(PostPoundsListActivity.this),tip,Toast.LENGTH_SHORT,true);
                       //mFromPage==1当前任务上传了榜单,上传榜单成功后结束定位if(MyApplication.mLocationService != null && mFromPage == 1) {
                        unRegistEvent(); //上传磅单结束后，就不需要监听 定位与 查看图片列表 里的 删除消息了
                        Log.i(TAG,"postFile 磅单已上传");
                        if(mOutWeighingListUrls != null) {
                            mOutWeighingListUrls.clear();
                        }
                        if(mReceiveWeighingListUrls != null) {
                            mReceiveWeighingListUrls.clear();
                        }
                        if(mListUrls != null){
                            mListUrls.clear();
                        }
                        mPoundsListInfo = null;
                       finish();
                    }
                });
            }
        });
    }
    @Override
    public int getContentViewId() {
        return R.layout.activity_post_pounds_list;
    }
    /**
     * 根据榜单状态，更新磅单UI页面的数据显示
     * @param data
     */
    private void updatePoundsUI(JsonPoundsState data) {
        mDataBinding.mainLayout.setVisibility(View.VISIBLE);
        mPoundState = data.getWeighsStatus();
        Log.e(TAG,"postFile check mPoundsState ="+mPoundState);
        if(mFromPage == 1){  //正常上传磅单页面
            if(mPoundState.equals("3")){  //出场榜单已上传，应该回显，并显示提货榜单上传UI
                mDataBinding.outPoundsShowLayout.setVisibility(View.VISIBLE);
                mDataBinding.recvPoundsLayout.setVisibility(View.VISIBLE);
                //回显出厂磅单text字段
                mDataBinding.tvCarNum.setText(data.getOutVehiclePlateNumber());
                mDataBinding.tvGrossWeightShow.setText(data.getOutGrossWeight());
                mDataBinding.tvTareWeightShow.setText(data.getOutTare());
                mDataBinding.tvPureWeightShow.setText(data.getOutNetWeight());
                mDataBinding.tvShowOutPoundsPostTime.setText(DateTimeUtils.timeStampToDateString(data.getCreateTime()));
                mDataBinding.setUnit(mUnit);
                mOutPoundsShowImgs  = data.getOutWeighingListUrls();
                showOutImgGrid(mOutPoundsShowImgs);
            }
            else if(mPoundState.equals("-1")) { //还未上传出厂榜单
                mDataBinding.outPoundsLayout.setVisibility(View.VISIBLE);
                mDataBinding.recvPoundsLayout.setVisibility(View.GONE);
            }
        }
        else{  //异常磅单页面
            mDataBinding.outPoundsLayout.setVisibility(View.VISIBLE);
            mDataBinding.recvPoundsLayout.setVisibility(View.VISIBLE);
        }
    }

    public void dismissPostImgLoading(){
        if (mLocProgressDialog != null && mLocProgressDialog.isShowing()) {
            mLocProgressDialog.dismiss();
            mLocProgressDialog = null;
        }
    }
    @Override
    public void onAllTaskEnd() {
        dismissPostImgLoading();
        Log.e(TAG,"postFile in onAllTaskEnd mPoundState="+mPoundState);
        List<UploadInfo> uploadInfos = UploadManager.getInstance(this).getAllTask();
        int taskSize = uploadInfos.size();
        if(taskSize == 0) {
            return;
        }
        else {
            int taskNums = 0;
            for (UploadInfo uploadInfo : uploadInfos) {
                if (uploadInfo.getState() != UploadManager.FINISH) {
                    MyLogCat.i(TAG,"postFile 所有上传线程结束，部分上传未完成");
                    break;
                }
                //上传正常的任务可以删除了，上传不正常的继续留在任务队列里，这样当再次点击上传的时候还可以继续上传刚才失败的那个文件
                taskNums++;
            }
            //所有图片上传完成后，才开始上传磅单信息（图片+文本字段）
            if(taskSize == taskNums) {
                MyLogCat.e(TAG,"postFile 上传完成所有图片");
                postPoundsInfo();
             //   clearSelectMedia(); //上传完成，则清理图和视频列表，否则不清理，可以继续上传列表中的文件
               //gxw- Toast.makeText(PostPoundsListActivity.this,"postFile finish 上传完成",Toast.LENGTH_SHORT).show();
            }
            uploadInfos.clear();  //清除所有任务对象
        }
        clearSelectMedia(); //目前，无论是否全部上传成功，都清除缓存
    }

    /**
     * 清除图片列表
     */
    public void clearSelectMedia() {
        //清除出厂磅单图片缓存
        if(mDataListOut != null) {
            mDataListOut.clear();
            if(mAdapterOut != null) {
                mAdapterOut.notifyDataSetChanged();
            }
        }
        //清除收货磅单图片缓存
        if(mDataListRecv != null) {
            mDataListRecv.clear();
            if(mAdapterRecv != null) {
                mAdapterRecv.notifyDataSetChanged();
            }
        }
        //清除回显磅单图片缓存
        if(mDataListOutShow != null) {
            mDataListOutShow.clear();
            if(mAdapterOutShow != null) {
                mAdapterOutShow.notifyDataSetChanged();
            }
        }

        if(mDataList != null){
            mDataList.clear();
        }
    }

    /**
     * 从相册选择照片，照相机拍照片
     */
    private class MySelPicItemClick implements View.OnClickListener {
        int mPoundsType = 0;
        MySelPicItemClick(int poundsType) {
            mPoundsType = poundsType;
        }
        @Override
        public void onClick(View v) {
            mSelectPicPopupWindow.dismiss();
            switch (v.getId()) {
                case R.id.takePhotoBtn: //去拍照
                    goTakePhoto(mPoundsType);
                    break;
                case R.id.pickPhotoBtn: //去相册
                    goAlbum(mPoundsType);
                    break;
                default:
                    break;
            }
        }
    }


    /**
     * 去系统相册
     */
    public void goAlbum(int poundsType) {
        //step1.获取相关权限
        final String[] permissionPickRequest = {Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE};
        RxPermissions permissionsPick = new RxPermissions(PostPoundsListActivity.this);
        permissionsPick.setLogging(true);
        permissionsPick.requestEachCombined(permissionPickRequest)
                .subscribe(new Consumer<Permission>() {
                    @Override
                    public void accept(Permission permission) throws Exception {
                        if (permission.granted) {//同意后调用
                            choosePhoto(poundsType);
                        } else if (permission.shouldShowRequestPermissionRationale) {
                            //拒绝，但没有选择  “以后不再询问”，以后申请权限，会继续弹出提示
                            MyLogCat.i(TAG, permission.name + "被拒绝");
                        } else {
                            //禁止，选择了“以后不再询问”，以后申请权限，将不会弹出提示
                            MyLogCat.i(TAG, permission.name + "被禁止");
                            RxjavaPermissionUtil.getInstance().alertOpenNavPermission(PostPoundsListActivity.this, permissionPickRequest);
                        }
                    }
                });
    }


    /**
     * 从系统相册里选择
     */
    private void choosePhoto(int poundsType) {
        Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
        photoPickerIntent.setType("image/*");
        int requestCode = (poundsType == 0 ? MyConstant.REQUESTCODE_PICK:MyConstant.REQUESTCODE_PICK_RECV);
        startActivityForResult(photoPickerIntent,requestCode);
    }


    /**
     * 去拍照
     */
    public void goTakePhoto(int poundsType) {
        //step1.先申请相关权限，相机与存储权限
        final String[] permissionRequest = {Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE};
        RxPermissions permissions = new RxPermissions(PostPoundsListActivity.this);
        permissions.setLogging(true);
        permissions.requestEachCombined(permissionRequest)
                .subscribe(new Consumer<Permission>() {
                    @Override
                    public void accept(Permission permission) throws Exception {
                        if (permission.granted) {
                            MyLogCat.i(TAG,"同意了权限");
                            //step2.拍照片
                            takePhoto(poundsType);
                        } else if (permission.shouldShowRequestPermissionRationale) {
                            //拒绝权限，但没有选择“以后不再询问”，以后申请权限，会继续弹出提示
                            MyLogCat.i(TAG,"拒绝了权限");
                        } else {
                            //禁止权限，但选择“以后不再询问”，以后申请权限，不会继续弹出提示
                            MyLogCat.i(TAG,"禁止了权限");
                            RxjavaPermissionUtil.getInstance().alertOpenNavPermission(PostPoundsListActivity.this, permissionRequest);
                        }
                    }
                });
    }

    /**
     * 为选择相册 or 拍照图片，创建保存目录
     */
    public void mkDirForPic() {
        picSaveDirectory = new File(MyApplication.PIC_DIRECTORY);
        if (!picSaveDirectory.exists()) {
            picSaveDirectory.mkdirs();
        }
    }
    /**
     * 拍照片
     */
    private void takePhoto(int poundsType) {
        if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            return;
        }
        //拍照获得的图片名为takePhotoPoundsList.jpg，与之对应的文件对象为takePhotoFile，图片文件将保存在picSaveDirectory目录下
        String fileName = "takePhotoPounds_"+DateTimeUtils.timeStampToDateString(System.currentTimeMillis())+".jpg";
        takePhotoFile = new File(picSaveDirectory, fileName);
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

        /**
         *  在Android7.0以上,使用FileProvider获取Uri,即需要本APP授权，因为相机和本APP是两个应用，应用之间共享目录（或全路径）需要本APP授权给相机应用,
         *  然后，相机应用才能将拍照得到的照片，保存至contentUri路径下，实质就是takePhotoFile的存放路径picSaveDirectory/takePhotoPoundsList.jpg（本APP创建的文件目录）
         */
        if (Build.VERSION.SDK_INT >= 24) {
            intent.setFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            Uri contentUri = FileProvider.getUriForFile(PostPoundsListActivity.this, getPackageName(), takePhotoFile);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, contentUri);
        } else {
            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(takePhotoFile));
        }
        //REQUESTCODE_CAMERA出货磅单拍照requestCode；   REQUESTCODE_CAMERA_RECV：收货磅单拍照
        int requestCode = (poundsType == IntentConstants.GRID_OUT_TYPE ? MyConstant.REQUESTCODE_CAMERA:MyConstant.REQUESTCODE_CAMERA_RECV);
        startActivityForResult(intent, requestCode);
    }


    /**
     * 裁剪图片
     * @param uri ：将要被裁剪的图片Uri路径
     */
    private void cropPhoto(Uri uri) {
        //裁剪成功的小图将放在picSaveDirectory目录下，路径为：picSaveDirectory/poundsListSmall.jpg
        cropSmallFile = new File(picSaveDirectory, "poundsListSmall.jpg");
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        intent.putExtra("outputX", 400); //裁剪区域宽、高
        intent.putExtra("outputY", 400);
        intent.putExtra("return-data", false);  //不用返回数据到一个Bitmap对象，节省性能
        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(cropSmallFile)); //裁剪成功的图片将输出到cropSmallFile路径下
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        intent.putExtra("noFaceDetection", true);
        intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        startActivityForResult(intent, MyConstant.REQUESTCODE_CUTTING);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {

        if(resultCode == RESULT_OK) {
            switch (requestCode) {
                case MyConstant.REQUESTCODE_CAMERA:  //从相机拍照返回后回调 for 出厂榜单
                    dealCameraPic(takePhotoFile,IntentConstants.GRID_OUT_TYPE);
                    break;
                case MyConstant.REQUESTCODE_CAMERA_RECV:  //从相机拍照返回后回调 for 收货榜单
                    dealCameraPic(takePhotoFile, IntentConstants.GRID_RECV_TYPE);
                    break;
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }


    /**
     * 显示、上传 拍照的图片
     * @param photoFile
     * @param poundsType: 磅单类型 0表示为出货磅单拍照； 1表示为收货磅单拍照
     */
    public void dealCameraPic(File photoFile,int poundsType) {
         compressPic(photoFile);
        String fileAbsPath = photoFile.getAbsolutePath();
        //出厂磅单图片，添加到出厂磅单图片列表
        if(poundsType == IntentConstants.GRID_OUT_TYPE){
            if (mDataListOut.size() < mMaxImgSize  && !TextUtils.isEmpty(fileAbsPath)) {
                ImageItem item = new ImageItem();
                item.sourcePath = fileAbsPath;
                mDataListOut.add(item);
                MyLogCat.i(TAG,"postFile mDataListOut.size()="+mDataListOut.size());
            }
        }
        //收货磅单图片，添加到收货磅单图片列表
        else if(poundsType == IntentConstants.GRID_RECV_TYPE){
            if (mDataListRecv.size() <mMaxImgSize  && !TextUtils.isEmpty(fileAbsPath)) {
                ImageItem item = new ImageItem();
                item.sourcePath = fileAbsPath;
                mDataListRecv.add(item);
                MyLogCat.i(TAG,"postFile mDataListRecv.size()="+mDataListRecv.size());
            }
        }
        notifyDataChanged(poundsType);
    }

    /**
     * 适配api19及以上,根据uri获取图片的绝对路径
     * @param context 上下文对象
     * @param uri     图片的Uri
     * @return 如果Uri对应的图片存在, 那么返回该图片的绝对路径, 否则返回null
     */
    @SuppressLint("NewApi")
    public static String getRealPathFromUriAboveApi19(Context context, Uri uri) {
        String filePath = null;
        if (DocumentsContract.isDocumentUri(context, uri)) {
            // 如果是document类型的 uri, 则通过document id来进行处理
            String documentId = DocumentsContract.getDocumentId(uri);
            if (isMediaDocument(uri)) { // MediaProvider
                // 使用':'分割
                String id = documentId.split(":")[1];
                String selection = MediaStore.Images.Media._ID + "=?";
                String[] selectionArgs = {id};
                filePath = getDataColumn(context, MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection, selectionArgs);
            } else if (isDownloadsDocument(uri)) { // DownloadsProvider
                Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(documentId));
                filePath = getDataColumn(context, contentUri, null, null);
            }
        } else if ("content".equalsIgnoreCase(uri.getScheme())){
            // 如果是 content 类型的 Uri
            filePath = getDataColumn(context, uri, null, null);
        } else if ("file".equals(uri.getScheme())) {
            // 如果是 file 类型的 Uri,直接获取图片对应的路径
            filePath = uri.getPath();
        }
        return filePath;
    }


    private static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) {
        String path = null;

        String[] projection = new String[]{MediaStore.Images.Media.DATA};
        Cursor cursor = null;
        try {
            cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null);
            if (cursor != null && cursor.moveToFirst()) {
                int columnIndex = cursor.getColumnIndexOrThrow(projection[0]);
                path = cursor.getString(columnIndex);
            }
        } catch (Exception e) {
            if (cursor != null) {
                cursor.close();
            }
        }
        return path;
    }


    /**
     * @param uri the Uri to check
     * @return Whether the Uri authority is MediaProvider
     */
    private static boolean isMediaDocument(Uri uri) {
        return "com.android.providers.media.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri the Uri to check
     * @return Whether the Uri authority is DownloadsProvider
     */
    private static boolean isDownloadsDocument(Uri uri) {
        return "com.android.providers.downloads.documents".equals(uri.getAuthority());
    }



    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btPostPoundsList:   //上传磅单，先请求位置
                stopAllPostFileTask();
                postPoundsImgs();
                break;
            case R.id.btTaskDetail:
                if(TextUtils.isEmpty(mCurTaskId)) {
                    String tip = this.getResources().getString(R.string.task_id_not_empty);
                    MyToast.showToastCenter(new WeakReference<>(PostPoundsListActivity.this),tip,Toast.LENGTH_SHORT,true);
                    return;
                }
                Intent i = new Intent(this, TaskDetailActivity.class);
                i.putExtra("id",mCurTaskId);
                startActivity(i);
                break;
        }
    }


    /**
     * 上传磅单各张图片
     */
    public void postPoundsImgs() {
        if(mPoundState.equals("-1")){  //上传出厂磅单 多张图片
            boolean isOutTextOk = checkOutPoundsTextField();
            if(isOutTextOk){
                postOutPoundsImgList();
            }
        }
        else if(mPoundState.equals("3")){ //出厂已上传，这次是上传收货磅单图片
            boolean isRecvTextOk = checkRecvPoundsTextField();
            if(isRecvTextOk){
                postRecvPoundsImgList();
            }
        }
        else{  //异常磅单
            boolean isOutTextOk = checkOutPoundsTextField();
            boolean isRecvTextOk = checkRecvPoundsTextField();
            if(isOutTextOk && isRecvTextOk){
                postExcePoundsImgList();
            }
        }
    }
    private void postExcePoundsImgList() {
        int outImgSize = mDataListOut.size();
        int recvImgSize = mDataListRecv.size();
        //异常磅单，出厂和收货都得上传图片，缺1不可
        if(outImgSize == 0){
            String tip = this.getResources().getString(R.string.please_add_out_img);
            MyToast.showToastCenter(new WeakReference<>(PostPoundsListActivity.this),tip,Toast.LENGTH_LONG,true);
            return ;
        }

        if(recvImgSize == 0){
            String tip = this.getResources().getString(R.string.please_add_recv_img);
            MyToast.showToastCenter(new WeakReference<>(PostPoundsListActivity.this),tip,Toast.LENGTH_LONG,true);
            return ;
        }
        postOutPoundsImgList();
        postRecvPoundsImgList();
    }

    private class MyUploadListener extends UploadListener<UploadInfo> {
        @Override
        public void onProgress(UploadInfo uploadInfo) {
            MyLogCat.i(TAG,"postFile onProgress"+uploadInfo.getProgress());
            //gxw-Log.e("MyUploadListener", "onProgress:" + uploadInfo.getFileName() + " " + uploadInfo.getTotalLength() + " " + uploadInfo.getUploadLength() + " " + uploadInfo.getProgress());
        /* gxw-s 暂时不显示进度start
            GridImageAdapter.ViewHolder view = (GridImageAdapter.ViewHolder) getUserTag();
            holder = view;
            holder.refresh(uploadInfo);
            gxw-e 暂时不显示进度start*/
        }

        @Override
        public void onFinish(UploadInfo t) {
            MyLogCat.i(TAG,"postFile in onFinish mPoundState="+mPoundState);
        }

        @Override
        public void onError(UploadInfo uploadInfo, String errorMsg, Exception e) {
            MyLogCat.e(TAG, "postFile onError:" + errorMsg);

            if(errorMsg != null){
                WeakReference<Context> contextWeakReference = new WeakReference<>(PostPoundsListActivity.this);
                MyToast.showToastCenter(contextWeakReference,errorMsg,Toast.LENGTH_SHORT,true);
            }
            if(e != null) {
                e.printStackTrace();
            }
        }
        @Override
        public UploadInfo parseNetworkResponse(Response response) throws Exception {
            UploadInfo uploadInfo = new UploadInfo();
            Response.Builder builder = response.newBuilder();
            Response clone = builder.build();
            ResponseBody body = clone.body();

            if(body != null) {
                String jsonData = body.string();
                JSONObject postFileJson = new JSONObject(jsonData);
                int code = postFileJson.getInt("code");
                String msg = postFileJson.getString("message");

                if(code == 200) {
                    uploadInfo.setState(UploadManager.FINISH);
                    FileUrlBean fileUrlBean = new FileUrlBean();
                    JSONObject postFileData = postFileJson.getJSONObject("data");
                    fileUrlBean.setFileUrl(postFileData.getString("fileUrl"));
                    fileUrlBean.setThumbFileUrl(postFileData.getString("thumbFileUrl"));
                    fileUrlBean.setType(postFileData.getInt("type"));
                    if(mPoundState.equals("-1")){
                          mOutWeighingListUrls.add(fileUrlBean);
                          MyLogCat.i(TAG,"postFile mOutWeighingListUrls.size="+mOutWeighingListUrls.size());
                    }
                    else if(mPoundState.equals("3")){  //收货磅单图片
                        mReceiveWeighingListUrls.add(fileUrlBean);
                        MyLogCat.i(TAG,"postFile mWeighingListUrls.size="+mListUrls.size());
                    }
                    else{
                        mListUrls.add(fileUrlBean);
                        MyLogCat.i(TAG,"postFile mListUrls.size="+mListUrls.size());
                    }
                }
                else{
                    uploadInfo.setState(UploadManager.ERROR); //上传成功
                    uploadInfo.setErrMsg(msg);
                }
                /*判断单张图片上传是否成功
                JSONObject data =  new JSONObject(content);
                String msg = data.getString("msg");
                int status = data.getInt("status");
                if(status == 0) {
                    uploadInfo.setState(UploadManager.ERROR); //上传成功
                }
                else {
                    uploadInfo.setState(UploadManager.FINISH);
                }*/
            }
            return uploadInfo;
        }
    }


    public void showPostImgLoadingDlg(){
        if (mLocProgressDialog == null) {
            mLocProgressDialog = new ProgressDialog(this);
        }
        if(!PostPoundsListActivity.this.isFinishing()){
            String strUploadingImg = this.getResources().getString(R.string.uploading_img);
            mLocProgressDialog.setMessage(strUploadingImg);
            mLocProgressDialog.show();
        }
    }
    /**
     * 上传出厂磅单图片列表
     */
    public boolean postOutPoundsImgList(){
        //多线程池 上传多张出厂磅单图片
         int size = mDataListOut.size();
         MyLogCat.i(TAG,"postFile out imgSize="+size);
         if(size > 0){
             //准备用来存储 “文件服务器” 生成并返回的图片url地址，FileUrlBean里包括一张图片的原图url地址，缩略图url地址
             showPostImgLoadingDlg();
             for(int i = 0; i < size; i++){
                 MyUploadListener listener = new MyUploadListener();
                 ImageItem imageItem = mDataListOut.get(i);
                 String filePath = imageItem.sourcePath;

                 //请求除登录以外的接口，都要带上token
                 String token = User.getToken();
                 String tokenHead = User.getTokenHead();
                 String auth = tokenHead + " "+token;
                 MyLogCat.i(TAG,"auth="+auth);

                 HashMap map = new HashMap<String,String>();
                 map.put("Authorization",auth);
                 UploadManager.getInstance(this).addTask(MyConstant.POST_FILE+"?isThumb=true", new File(filePath), "file",map, listener);
             }
             mDataListOut.clear();
             return true;
         }else{
             String tip = this.getResources().getString(R.string.please_add_out_img);
             MyToast.showToastCenter(new WeakReference<>(PostPoundsListActivity.this),tip,Toast.LENGTH_SHORT,true);
             return false;
         }


    }

    /**
     * 上传出收货磅单图片列表
     */
    public void postRecvPoundsImgList(){

        int size = mDataListRecv.size();
        MyLogCat.i(TAG,"postFile recv imgSize="+size);

        if(size > 0){
            showPostImgLoadingDlg();
            for(int i = 0; i <size; i++){
                MyUploadListener listener = new MyUploadListener();
                ImageItem imageItem = mDataListRecv.get(i);
                String filePath = imageItem.sourcePath;

                //请求除登录以外的接口，都要带上token
                String token = User.getToken();
                String tokenHead = User.getTokenHead();
                String auth = tokenHead + " "+token;
                MyLogCat.i(TAG,"auth="+auth);
                HashMap map = new HashMap<String,String>();
                map.put("Authorization",auth);
                UploadManager.getInstance(this).addTask(MyConstant.POST_FILE+"?isThumb=true", new File(filePath), "file",map, listener);
            }
            mDataListRecv.clear();
        }
        else{

            String tip = this.getResources().getString(R.string.please_add_recv_img);
            MyToast.showToastCenter(new WeakReference<>(PostPoundsListActivity.this),tip,Toast.LENGTH_SHORT,true);
        }
    }


    /**
     * 上c
     */
    public void postPoundsInfo(){
        registEvent();
        mPoundsListInfo = getInput();
        if(mPoundsListInfo != null) {
            Log.i(TAG,"postFile requestMyLocation");
           requestMyLocation(true);  //这里后续可以优化一下，加个请求超时判断
        }
    }

    /**
     * 获取榜单信息对象
     * @return
     */
    private PoundsListBean getInput() {
        Log.i(TAG,"postFile getInput mPoundsState == "+mPoundState);
        PoundsListBean poundsListBean = null;
        if(mFromPage != 2){  //正常磅单上传
            if(mPoundState.equals("-1")){   //未上传任何磅单，这次将上传出厂磅单
                poundsListBean = getOutFactoryPoundsListBean(false);
            }
            else if(mPoundState.equals("3")){  //出货磅单已上传，这次将上传收货磅单
                poundsListBean = getRecvFactoryPoundsListBean(false);
            }

        }else{  //异常磅单重新上传
            poundsListBean = getExcepPoundsData();
        }

        return poundsListBean;
    }

    /**
     * 得到异常磅单要提交的磅单数据对象
     * @return
     */
    public PoundsListBean getExcepPoundsData(){
        PoundsListBean exceptionPoundsListBean;
        //step1.得到出厂和收货磅单数据对象
        PoundsListBean  outPoundsListBean = getOutFactoryPoundsListBean(true);
        PoundsListBean  recvPoundsListBean = getRecvFactoryPoundsListBean(true);
        if(outPoundsListBean == null || recvPoundsListBean == null){
            MyLogCat.e(TAG,"postFile 异常磅单所填写的数据有误");
            return null;
        }
        else{
            //step2.目前合并出厂和收货磅单数据 就是异常磅单数据
            exceptionPoundsListBean = getExceptionPoundsListBean(outPoundsListBean,recvPoundsListBean);
        }
        return exceptionPoundsListBean;
    }

    /**
     * @return PoundsListBean 将要上传的异常磅单数据（出厂磅单+收货磅单）
     */
    public PoundsListBean getExceptionPoundsListBean(PoundsListBean out,PoundsListBean recv){
        if(out == null || recv == null){
            return null;
        }
        PoundsListBean poundsListBean = new PoundsListBean();
        poundsListBean.taskId = mCurTaskId;

        //出厂
        poundsListBean.outWeighingListUrls = out.outWeighingListUrls;
        poundsListBean.outVehiclePlateNumber = out.outVehiclePlateNumber;
        poundsListBean.outGrossWeight =  out.outGrossWeight;
        poundsListBean.outTare = out.outTare;
        poundsListBean.outNetWeight = out.outNetWeight;
        poundsListBean.laLat = "";
        poundsListBean.laLng = "";

        //收货
        poundsListBean.receiveWeighingListUrls = recv.receiveWeighingListUrls;
        poundsListBean.receiveVehiclePlateNumber =  recv.receiveVehiclePlateNumber;
        poundsListBean.receiveGrossWeight = recv.receiveGrossWeight;
        poundsListBean.receiveTare = recv.receiveTare;
        poundsListBean.receiveNetWeight = recv.receiveNetWeight;
        poundsListBean.uaLat = "";
        poundsListBean.uaLng = "";
        poundsListBean.type = null;
        return poundsListBean;
    }
    /**
     * 检查要上传的出厂磅单数据是否完整，并将数据以对象返回
     * @return PoundsListBean 将要上传的出厂磅单数据
     */
    public PoundsListBean getOutFactoryPoundsListBean(boolean isException){

        //step1 获取出厂磅单数据
        String carNum = mDataBinding.edtCarNum.getText().toString();
        String grossWeight = mDataBinding.edtGrossWeight.getText().toString();
        String tareWeight = mDataBinding.edtTareWeight.getText().toString();
        String pureWeight = mDataBinding.edtPureWeight.getText().toString();
        //step2 检查出厂磅单数据
        boolean isValide = checkOutFactoryData(carNum,grossWeight,tareWeight,pureWeight,mOutWeighingListUrls,isException);
        if(!isValide){
            MyLogCat.e(TAG,"postFile 有问题：出货磅单数据有误");
            return null;
        }
        //step3 封装出厂磅单数据为对象并返回
        PoundsListBean poundsListBean = new PoundsListBean();
        poundsListBean.taskId = mCurTaskId;
        poundsListBean.outWeighingListUrls = mOutWeighingListUrls;
        poundsListBean.outVehiclePlateNumber = carNum;
        poundsListBean.outGrossWeight = grossWeight;
        poundsListBean.outTare = tareWeight;
        poundsListBean.outNetWeight = pureWeight;
        poundsListBean.laLat = "";
        poundsListBean.laLng = "";
        poundsListBean.type = "3"; //还未上传任何磅单，则这次上传 “出厂磅单”,提交给服务器的type应该是3
        return poundsListBean;
    }

    /**
     * 封装收货磅单数据对象
     */
    public PoundsListBean getRecvFactoryPoundsListBean(boolean isException){

        //step1 获取收货磅单数据
        String carNum2 = mDataBinding.edtCarNum2.getText().toString();
        String grossWeight2 = mDataBinding.edtGrossWeight2.getText().toString();
        String tareWeight2 = mDataBinding.edtTareWeight2.getText().toString();
        String pureWeight2 = mDataBinding.edtPureWeight2.getText().toString();

        //step2 检查收货磅单数据
        boolean isValide = checkRecvFactoryData(carNum2,grossWeight2,tareWeight2,pureWeight2,mReceiveWeighingListUrls,isException);
        if(!isValide){
            MyLogCat.e(TAG,"postFile 有问题，收货磅单数据");
            return null;
        }
        //step3 封装收货磅单数据
        PoundsListBean poundsListBean =  new PoundsListBean();
        poundsListBean.taskId = mCurTaskId;
        poundsListBean.receiveWeighingListUrls = mReceiveWeighingListUrls;
        poundsListBean.receiveVehiclePlateNumber = carNum2;
        poundsListBean.receiveGrossWeight = grossWeight2;
        poundsListBean.receiveTare = tareWeight2;
        poundsListBean.receiveNetWeight = pureWeight2;
        poundsListBean.uaLat = "";
        poundsListBean.uaLng = "";
        poundsListBean.type = "0";      //已上传出厂磅单，则这次上传 “收货磅单”
        return poundsListBean;
    }

    /**
     * 检查出厂输入的文本字段
     * @return
     */
    public boolean checkOutPoundsTextField(){
        String carNum = mDataBinding.edtCarNum.getText().toString();
        String grossWeight = mDataBinding.edtGrossWeight.getText().toString();
        String tareWeight = mDataBinding.edtTareWeight.getText().toString();
        String pureWeight = mDataBinding.edtPureWeight.getText().toString();
        //检查出厂各字段的合法性
        // 车牌号
        if(TextUtils.isEmpty(carNum)) {
            String tip = this.getResources().getString(R.string.car_num_out_not_empty);
            MyToast.showToastCenter(new WeakReference<>(PostPoundsListActivity.this),tip,Toast.LENGTH_SHORT,true);
            return false;
        }
         /*   else{
                boolean isVehicleNum = DateTimeUtils.isVehicleNumber(carNum);
                if(!isVehicleNum){
                    Toast.makeText(PostPoundsListActivity.this,R.string.car_num_invalide,Toast.LENGTH_SHORT).show();
                    return null;
                }
            }*/
        //毛重
        if(TextUtils.isEmpty(grossWeight)) {
            String tip = this.getResources().getString(R.string.gross_weight_not_empty);
            MyToast.showToastCenter(new WeakReference<>(PostPoundsListActivity.this),tip,Toast.LENGTH_SHORT,true);
            return false;
        }
        //皮重
        if(TextUtils.isEmpty(tareWeight)) {
            String tip = this.getResources().getString(R.string.tare_weight_not_empty);
            MyToast.showToastCenter(new WeakReference<>(PostPoundsListActivity.this),tip,Toast.LENGTH_SHORT,true);
            return false;
        }
        //净重
        if(TextUtils.isEmpty(pureWeight)) {
            String tip = this.getResources().getString(R.string.pure_weight_not_empty);
            MyToast.showToastCenter(new WeakReference<>(PostPoundsListActivity.this),tip,Toast.LENGTH_SHORT,true);
            return false;
        }
        if(TextUtils.isEmpty(mCurTaskId)) {
            String tip = this.getResources().getString(R.string.task_id_not_empty);
            MyToast.showToastCenter(new WeakReference<>(PostPoundsListActivity.this),tip,Toast.LENGTH_SHORT,true);
            return  false;
        }
        return true;
    }


    /**
     * 检查出厂输入的文本字段
     * @return
     */
    public boolean checkRecvPoundsTextField(){
        String carNum2 = mDataBinding.edtCarNum2.getText().toString();
        String grossWeight2 = mDataBinding.edtGrossWeight2.getText().toString();
        String tareWeight2 = mDataBinding.edtTareWeight2.getText().toString();
        String pureWeight2 = mDataBinding.edtPureWeight2.getText().toString();
        //检查出厂各字段的合法性
        // 车牌号
        if(TextUtils.isEmpty(carNum2)) {
            String tip = this.getResources().getString(R.string.car2_num_not_empty);
            MyToast.showToastCenter(new WeakReference<>(PostPoundsListActivity.this),tip,Toast.LENGTH_SHORT,true);
            return false;
        }
         /*   else{
                boolean isVehicleNum = DateTimeUtils.isVehicleNumber(carNum);
                if(!isVehicleNum){
                    Toast.makeText(PostPoundsListActivity.this,R.string.car_num_invalide,Toast.LENGTH_SHORT).show();
                    return null;
                }
            }*/
        //毛重
        if(TextUtils.isEmpty(grossWeight2)) {
            String tip = this.getResources().getString(R.string.gross2_weight_not_empty);
            MyToast.showToastCenter(new WeakReference<>(PostPoundsListActivity.this),tip,Toast.LENGTH_SHORT,true);
            return false;
        }
        //皮重
        if(TextUtils.isEmpty(tareWeight2)) {
            String tip = this.getResources().getString(R.string.tare2_weight_not_empty);
            MyToast.showToastCenter(new WeakReference<>(PostPoundsListActivity.this),tip,Toast.LENGTH_SHORT,true);
            return false;
        }
        //净重
        if(TextUtils.isEmpty(pureWeight2)) {
            String tip = this.getResources().getString(R.string.pure2_weight_not_empty);
            MyToast.showToastCenter(new WeakReference<>(PostPoundsListActivity.this),tip,Toast.LENGTH_SHORT,true);
            return false;
        }
        if(TextUtils.isEmpty(mCurTaskId)) {
            String tip = this.getResources().getString(R.string.task_id_not_empty);
            MyToast.showToastCenter(new WeakReference<>(PostPoundsListActivity.this),tip,Toast.LENGTH_SHORT,true);
            return  false;
        }
        return true;
    }
    /**
     * 检查出货磅单数据是否合法
     * @return true合法，FALSE不合法
     */
    public boolean checkOutFactoryData(String carNum,String grossWeight,String tareWeight,String pureWeight,
                                       ArrayList<FileUrlBean> outWeighingListUrls,boolean isExceptionPounds){
        //检查出厂各字段的合法性
        // 车牌号
        if(TextUtils.isEmpty(carNum)) {

            String tip = this.getResources().getString(R.string.car_num_out_not_empty);
            MyToast.showToastCenter(new WeakReference<>(PostPoundsListActivity.this),tip,Toast.LENGTH_SHORT,true);
            return false;
        }
         /*   else{
                boolean isVehicleNum = DateTimeUtils.isVehicleNumber(carNum);
                if(!isVehicleNum){
                    Toast.makeText(PostPoundsListActivity.this,R.string.car_num_invalide,Toast.LENGTH_SHORT).show();
                    return null;
                }
            }*/
        //毛重
        if(TextUtils.isEmpty(grossWeight)) {
            String tip = this.getResources().getString(R.string.gross_weight_not_empty);
            MyToast.showToastCenter(new WeakReference<>(PostPoundsListActivity.this),tip,Toast.LENGTH_SHORT,true);
            return false;
        }
        //皮重
        if(TextUtils.isEmpty(tareWeight)) {
            String tip = this.getResources().getString(R.string.tare_weight_not_empty);
            MyToast.showToastCenter(new WeakReference<>(PostPoundsListActivity.this),tip,Toast.LENGTH_SHORT,true);
            return false;
        }
        //净重
        if(TextUtils.isEmpty(pureWeight)) {
            String tip = this.getResources().getString(R.string.pure_weight_not_empty);
            MyToast.showToastCenter(new WeakReference<>(PostPoundsListActivity.this),tip,Toast.LENGTH_SHORT,true);
            return false;
        }
        if(TextUtils.isEmpty(mCurTaskId)) {
            String tip = this.getResources().getString(R.string.task_id_not_empty);
            MyToast.showToastCenter(new WeakReference<>(PostPoundsListActivity.this),tip,Toast.LENGTH_SHORT,true);
            return  false;
        }

        if(isExceptionPounds) {  //异常磅单重新提交时，要上传的出厂图片列表，目前限制为一张
            if (mListUrls != null && mListUrls.size() == 0) {
                Log.i(TAG,"postFile mListUrls == null");
                String tip = this.getResources().getString(R.string.out2_pound_not_empty);
                MyToast.showToastCenter(new WeakReference<>(PostPoundsListActivity.this),tip,Toast.LENGTH_SHORT,true);
                return false;
            }
            else{
                outWeighingListUrls.add(mListUrls.get(0));
                MyLogCat.i(TAG,"postFile exception mOutWeighingListUrls.size="+mOutWeighingListUrls.size());
            }
        }
        else{
            //出货磅单多张图片URL地址
            if(outWeighingListUrls == null || outWeighingListUrls.size() == 0){
                Log.i(TAG,"postFile mOutWeighingListUrls == null");
                String tip = this.getResources().getString(R.string.out2_pound_not_empty);
                MyToast.showToastCenter(new WeakReference<>(PostPoundsListActivity.this),tip,Toast.LENGTH_SHORT,true);
                return false;

            }
        }
        return true;
    }

    /**
     * 检查收货磅单数据是否合法
     * @return true合法，FALSE不合法
     */
    public boolean checkRecvFactoryData(String carNum2,String grossWeight2,String tareWeight2,String pureWeight2,
                                        ArrayList<FileUrlBean> recvWeighingListUrls,boolean isExceptionPounds){
        //收货榜单字段
        // 车牌号
        if(TextUtils.isEmpty(carNum2)) {
            String tip = this.getResources().getString(R.string.car2_num_not_empty);
            MyToast.showToastCenter(new WeakReference<>(PostPoundsListActivity.this),tip,Toast.LENGTH_SHORT,true);
            return false;
        }
        //毛重
        if(TextUtils.isEmpty(grossWeight2)) {
            String tip = this.getResources().getString(R.string.gross2_weight_not_empty);
            MyToast.showToastCenter(new WeakReference<>(PostPoundsListActivity.this),tip,Toast.LENGTH_SHORT,true);
            return false;
        }
        //皮重
        if(TextUtils.isEmpty(tareWeight2)) {
            String tip = this.getResources().getString(R.string.tare2_weight_not_empty);
            MyToast.showToastCenter(new WeakReference<>(PostPoundsListActivity.this),tip,Toast.LENGTH_SHORT,true);
            return false;
        }
        //净重
        if(TextUtils.isEmpty(pureWeight2)) {
            String tip = this.getResources().getString(R.string.pure2_weight_not_empty);
            MyToast.showToastCenter(new WeakReference<>(PostPoundsListActivity.this),tip,Toast.LENGTH_SHORT,true);
            return false;
        }

        if(TextUtils.isEmpty(mCurTaskId)) {
            String tip = this.getResources().getString(R.string.task_id_not_empty);
            MyToast.showToastCenter(new WeakReference<>(PostPoundsListActivity.this),tip,Toast.LENGTH_SHORT,true);
            return  false;
        }

        if(isExceptionPounds) {  //异常磅单重新提交时，要上传的收货磅单图片列表，目前限制为一张
            if (mListUrls != null && mListUrls.size() < 2) {
                Log.i(TAG,"postFile mListUrls recv == null || recv.size < 2");
                String tip = this.getResources().getString(R.string.out2_pound_not_empty);
                MyToast.showToastCenter(new WeakReference<>(PostPoundsListActivity.this),tip,Toast.LENGTH_SHORT,true);
                return false;
            }
            else{
                recvWeighingListUrls.add(mListUrls.get(1));
                MyLogCat.i(TAG,"postFile exception mOutWeighingListUrls.size="+mOutWeighingListUrls.size());
            }
        }
        //收货磅单多张图片URL地址
        if(recvWeighingListUrls == null || recvWeighingListUrls.size() == 0){
            Log.i(TAG,"postFile recvWeighingListUrls == null");
            String tip = this.getResources().getString(R.string.out2_pound_not_empty);
            MyToast.showToastCenter(new WeakReference<>(PostPoundsListActivity.this),tip,Toast.LENGTH_SHORT,true);
            return false;
        }
        return true;
    }


    /**
     * 弹出选择图片菜单窗口
     */
    public void showSelPicWindow(int poundsType) {
        MySelPicItemClick selectPicitemsOnClick = new MySelPicItemClick(poundsType);
        mSelectPicPopupWindow = new SelectPicPopupWindow(this, selectPicitemsOnClick,true);
        mSelectPicPopupWindow.showAtLocation(findViewById(R.id.mainLayout), Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
    }

    /**
     * 再次压缩裁剪后的图片，并替换初步裁剪出来的图片
     * @param photoFile
     * @return
     */
    public void compressPic(File photoFile) {
        if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            return;
        }
        String photoPath = photoFile.getAbsolutePath();
        Bitmap bitmap = BitmapFactory.decodeFile(photoPath);
        try {
            FileOutputStream cropedFileStream = new FileOutputStream(photoFile);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 20, cropedFileStream);//25目前是最佳，15实地测试也能看清，稍微模糊，20也还行
            cropedFileStream.flush();
            cropedFileStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}